import { isRef, onMounted, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import tippy from 'tippy.js'
import type { Instance as TippyInstance, Placement as TippyPlacement } from 'tippy.js'

interface TooltipOptions {
  content: string
  placement?: TippyPlacement
  trigger?: string
  theme?: string
}

export function useTooltip(
  el: HTMLElement | Ref<HTMLElement | null | undefined>,
  opts: TooltipOptions
) {
  const props = Object.assign(
    {
      placement: 'top',
      trigger: 'mouseenter focus',
      theme: 'light-border'
    },
    opts
  )

  const tp: { instance: TippyInstance | null } = { instance: null }

  onMounted(() => {
    const e: HTMLElement | null | undefined = isRef(el) ? el.value : el
    if (e) {
      tp.instance = tippy(e, props)
    }
  })
  onUnmounted(() => {
    tp.instance?.destroy()
  })
}
